<template>
  <div class="seq-flow-config">
    <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="条件类型" required>
        <a-select v-model:value="formData.type" style="width: 100%">
          <a-select-option value="expression">表达式</a-select-option>
          <a-select-option value="script">脚本</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="条件值" required>
        <a-textarea
          v-model:value="formData.value"
          :rows="4"
          placeholder="请输入条件表达式"
        />
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { computed, onMounted, ref, watch } from 'vue'
import { useBpmnModeler, useBpmnSelectedElem } from '/@/config/app.hooks'

export default {
  name: 'SeqFlowConfig',
  setup() {
    const bpmnModeler = useBpmnModeler()
    const bpmnSelectedElem = useBpmnSelectedElem()

    const formData = ref({
      type: 'expression',
      value: ''
    })

    const updateFormData = () => {
      const selectedElem = bpmnSelectedElem.value
      if (!selectedElem) {
        return
      }
      const bo = selectedElem.businessObject
      const conditionExpression = bo.get('conditionExpression')
      if (conditionExpression) {
        formData.value = {
          type: conditionExpression.language === 'groovy' ? 'script' : 'expression',
          value: conditionExpression.body || ''
        }
      }
    }

    watch(() => bpmnSelectedElem.value, () => {
      updateFormData()
    }, { immediate: true })

    watch(() => formData.value, (val) => {
      const selectedElem = bpmnSelectedElem.value
      if (!selectedElem) {
        return
      }
      const modeling = bpmnModeler.value.get('modeling')
      const moddle = bpmnModeler.value.get('moddle')
      const conditionExpression = moddle.create('bpmn:FormalExpression', {
        body: val.value,
        language: val.type === 'script' ? 'groovy' : undefined
      })
      modeling.updateProperties(selectedElem, {
        conditionExpression
      })
    }, { deep: true })

    return {
      formData
    }
  }
}
</script>

<style scoped>
.seq-flow-config {
  padding: 12px;
}
</style>
